package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //设备是否发生故障
        if (vmStatusContract == null || vmStatusContract.getStatusInfo() == null || vmStatusContract.getStatusInfo().size() <= 0)
            return;
        //是否正常
        if (vmStatusContract.getStatusInfo().stream().anyMatch(s -> s.isStatus() == false)) {

            try {
                //根据售货机编号查询售货机
                var vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());

                //查询工单量最少的
                var leastUser = taskService.getLeastUser(vmInfo.getRegionId(), true);
                //创建工单对象
                TaskViewModel taskViewModel = new TaskViewModel();
                //售货机编号
                taskViewModel.setInnerCode(vmInfo.getInnerCode());
                //工单类型
                taskViewModel.setCreateType(1);
                //描述
                taskViewModel.setDesc("自动维修工单");
                //维修工单
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
                //执行人
                taskViewModel.setUserId(leastUser);
                //创建工单
                taskService.createTask(taskViewModel);

            } catch (Exception e) {
                log.error("创建自动工单失败, msgis:" + jsonMsg);
            }

        }
    }
}
